#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include "Common.hpp"

const std::string gpipeFile = "./fifo |";

const int gdefaultfd = -1;
const int gForRead = O_RDONLY;
const int gForWrite = O_WRONLY;

int OpenPipeHelper(int flag)
{
    int fd = ::open(gpipeFile.c_str(), flag);
    if (fd < 0)
    {
        std::cerr << "open error" << std::endl;
        return -1;
    }
    return fd;
}

class Fifo
{
private:
    void OpenPipe(int flag)
    {
        _fd = OpenPipeHelper(flag);
        if (_fd < 0)
        {
            std::cerr << "open error" << std::endl;
        }
        std::cout << "open success" << std::endl;
    }

public:
    Fifo() : _fd(gdefaultfd)
    {
    }
    void FifoInit()
    {
        umask(0);
        // 由服务端创建管道
        int n = mkfifo(gpipeFile.c_str(), gmode);

        if (n < 0)
        {
            std::cerr << "mkfifo error" << std::endl;
            return;
        }
        std::cout << "mkfifo success" << std::endl;
    }
    void FifoDelete()
    {
        int n = ::unlink(gpipeFile.c_str());
        if (n < 0)
        {
            std::cerr << "unlink error" << std::endl;
            return;
        }
        std::cout << "unlink success" << std::endl;
    }
    void OpenForRead()
    {
        OpenPipe(gForRead);
    }
    void OpenForWrite()
    {
        OpenPipe(gForWrite);
    }
    int Wait()
    {
        int code = 0;
        int n = ::read(_fd,&code,sizeof(code));
        if(n == 0)//管道已关闭
        {
            return 1;
        }
        else if(n == sizeof(code))
        {
            return 0;
        }
        else return 2;

    }
    void Sginal()
    {
        int code = 1;
        ::write(_fd,&code,sizeof(code));
    }

    ~Fifo()
    {
        if (_fd >= 0)
            ::close(_fd);
    }

private:
    int _fd;
} fifo;